package com.gzz.service;

import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClient;
import com.aliyun.oss.OSSClientBuilder;
import com.gzz.utils.OssUtils;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.UUID;

@Service
public class OssUploadService {



	public String uploadFile(MultipartFile multipartFile,String dir){
		// Endpoint以华东1（杭州）为例，其它Region请按实际情况填写。
		String endpoint = OssUtils.endPoint;
		// 阿里云账号AccessKey拥有所有API的访问权限，风险很高。强烈建议您创建并使用RAM用户进行API访问或日常运维，请登录RAM控制台创建RAM用户。
		String accessKeyId = OssUtils.accessKeyId;
		String accessKeySecret = OssUtils.accessKeySecret;
		// 填写Bucket名称，例如examplebucket。
		String bucketName = "gzz-project-file";
		// 填写Object完整路径，完整路径中不能包含Bucket名称，例如exampledir/exampleobject.txt。
		String objectName = "exampledir/exampleobject.txt";

		// 创建OSSClient实例。
		OSS ossClient =null;

		try {
			ossClient = new OSSClientBuilder().build(endpoint,accessKeyId,accessKeySecret);
			InputStream inputStream = multipartFile.getInputStream();

			String originalFilename = multipartFile.getOriginalFilename();
			String fileName = UUID.randomUUID().toString();

			String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));

			String newName = fileName+suffix;

			String finalUrl = dir+"/"+newName;

			ossClient.putObject(bucketName,finalUrl,inputStream);

			return "https://"+bucketName+"."+endpoint+"/"+finalUrl;




		} catch (Exception oe) {
			return "error";
		}  finally {
			if (ossClient != null) {
				ossClient.shutdown();
			}
		}

	}
}
